/*
 * @Author: jiu yin
 * @Date: 2024-05-17 16:28:52
 * @LastEditTime: 2024-06-24 15:40:02
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \studio-web-admin\src\utils\webSocket\index.js
 * jiu
 */
import { deviceList } from "./common"
import { getWsStatus, setWsStatus } from "@/utils/sessionStorage"
import { setWsHost, getWsHost } from "@/utils/localStorage"

// const socketUrl = "ws://192.168.1.167:9060"; // WebSocket服务器地址
let socketUrl = sessionStorage.getItem('socketUrl') || '';

const heartbeatInterval = 3000; // 心跳间隔时间，单位为毫秒
const reconnectInterval = 5000; // 重连间隔时间，单位为毫秒

export let socket;

let heartbeatTimer;
let reconnectTimer;
let ws_host = getWsHost()
//订阅消息
let socketNotify = {}
export const addSocketNotify = (key, value) => {
   socketNotify[key] = value
}
//删除订阅
export const removeSocketNotify = (key) => {
   delete socketNotify[key]
}


export function connect(socketUrl) {
   disconnect()//先断开

   try {
      socket = new WebSocket(socketUrl);
   } catch (e) {
      console.log(e, "socket连接异常")
   }

   // socket = new WebSocket(socketUrl);

   socket.onopen = function () {
      console.log("WebSocket连接已打开");
      setWsStatus({ status: 1, str: "播控服务连接成功" })
      deviceList() //查询设备列表
      // startHeartbeat();
   };

   socket.onmessage = function (event) {
      const message = JSON.parse(event.data);
      // 处理收到的消息
      for (let key in socketNotify) {
         socketNotify[key](message);
      }

   };

   socket.onclose = function (event) {
      console.log("WebSocket连接已关闭");
      setWsStatus({ status: 2, str: "播控服务连接失败" })
      stopHeartbeat();
      reconnect();
   };

   socket.onerror = function (error) {
      console.error("WebSocket错误:", error);
      setWsStatus({ status: 2, str: "播控服务连接失败" })
      stopHeartbeat();
      reconnect();
   };
}
//心跳
function startHeartbeat() {
   heartbeatTimer = setInterval(function () {
      if (socket.readyState === WebSocket.OPEN) {
         // 发送心跳消息
         socket.send("heartbeat");
      }
   }, heartbeatInterval);
}
//清除心跳
function stopHeartbeat() {
   clearInterval(heartbeatTimer);
}
//重连
function reconnect() {
      reconnectTimer = setInterval(function () {
         if (socket.readyState === WebSocket.CLOSED) {
            console.log("尝试重新连接...");
            if (ws_host?.ws_host) connect(ws_host.ws_host)
         }
         if (socket.readyState === WebSocket.OPEN) {
            clearInterval(reconnectTimer);
            reconnectTimer = null;
         }
      }, reconnectInterval);
}
//在需要时手动断开连接
function disconnect() {
   if (socket) {
      socket.close();
   }
   clearInterval(reconnectTimer);
}

// 页面加载完成后调用连接函数
window.addEventListener("load", () => {
   if (ws_host?.ws_host) connect(ws_host.ws_host)
});